﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using FlyHorse.LIMS.Model;
using FlyHorse.LIMS.WinApp.LanguageResource;
using System.Data.Entity;

namespace FlyHorse.LIMS.WinApp.BaseManageForms.StandardCustomerFroms
{
    public partial class StandardCustomerMainForm : DevExpress.XtraEditors.XtraForm
    {
        BLL.StandardCustomerBll standardCustomerBll = new BLL.StandardCustomerBll();
        BLL.TestItemBll testItemBll = new BLL.TestItemBll();
        BLL.CustomerBll customerBll = new BLL.CustomerBll();
        BLL.GoodBll goodsBll = new BLL.GoodBll();
        OJCB4Entities db = new OJCB4Entities();
        public StandardCustomerMainForm()
        {
            InitializeComponent();
        }

        private void StandardCustomerMainForm_Load(object sender, EventArgs e)
        {
            //this.gridView1.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
            //this.gridView1.OptionsBehavior.Editable = false;
            //this.gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;



            var testItemList = testItemBll.LoadEntities(m => true).ToList();
            repositoryItemLookUpEdit3.DataSource = testItemList;
            repositoryItemLookUpEdit3.DisplayMember = "ChineseName";
            repositoryItemLookUpEdit3.ValueMember = "TestItemID";

            var goodsList = goodsBll.LoadEntities(m => true).ToList();
            repositoryItemLookUpEdit2.DataSource = goodsList;
            repositoryItemLookUpEdit2.DisplayMember = "GoodsName";
            repositoryItemLookUpEdit2.ValueMember = "GoodsID";

            var customerList = customerBll.LoadEntities(m => true).ToList();
            repositoryItemLookUpEdit1.DataSource = customerList;
            //repositoryItemLookUpEdit1.DisplayMember = "CustomerName";
            //repositoryItemLookUpEdit1.ValueMember = "CustomerID";

            gridView1.IndicatorWidth = 70;
            InitGrid();
        }

        private void InitGrid()
        {
            var models = db.StandardCustomers.Where(m => true).OrderBy(m => m.CustomerID).ThenBy(m => m.GoodsID).ThenBy(m => m.FormOrder).ToList();
            this.gridControl1.DataSource = models;
        }

        private void ButtonItem_add_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            StandardCustomerAddForm standardCustomerAddForm = new StandardCustomerAddForm(InitGrid);
            standardCustomerAddForm.ShowDialog();
        }


        private void ButtonItem_Edit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowEditForm();
        }

        private void ShowEditForm()
        {
            string id = Convert.ToString(this.gridView1.GetFocusedRowCellValue("StandardCustomerID"));
            StandardCustomer satandard = standardCustomerBll.LoadEntities(m => m.StandardCustomerID == id).FirstOrDefault();
            if (satandard != null)
            {
                StandardCustomerAddForm standardCustomerAddForm = new StandardCustomerAddForm(satandard, InitGrid);
                standardCustomerAddForm.ShowDialog();
            }
        }

        private void ButtonItem_Delete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int selectCount = gridView1.SelectedRowsCount;
            if (selectCount == 0)
            {
                XtraMessageBox.Show(ResourceOverall.SelectNull);
                return;
            }
            int[] selectRows = gridView1.GetSelectedRows();

            DialogResult result = XtraMessageBox.Show(ResourceOverall.ConfirmDelete, ResourceOverall.SystemWarningStr, MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (result == DialogResult.OK)
            {
                object sourse = this.gridControl1.DataSource;
                List<StandardCustomer> dataSourse = (List<StandardCustomer>)sourse;
                List<StandardCustomer> delList = new List<StandardCustomer>();

                for (int i = 0; i < selectRows.Length; i++)
                {
                    int row = selectRows[i];
                    int dataRowIndex = this.gridView1.GetDataSourceRowIndex(row);
                    StandardCustomer standard = dataSourse[dataRowIndex];
                    delList.Add(standard);
                }

                int resCount = BulkDelete(delList);
                if (resCount > 0)
                {
                    InitGrid();
                    XtraMessageBox.Show(ResourceOverall.DeleteSucceed);
                }
            }
        }

        //private void gridView1_DoubleClick(object sender, EventArgs e)
        //{
        //    ShowEditForm();
        //}

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            int row = e.RowHandle;
            int dataRowIndex = this.gridView1.GetDataSourceRowIndex(row);
            object sourse = this.gridControl1.DataSource;
            List<StandardCustomer> dataSourse = (List<StandardCustomer>)sourse;
            StandardCustomer standard = dataSourse[dataRowIndex];

            if (!String.IsNullOrEmpty(standard.MinValue))
            {
                try
                {
                    Convert.ToDouble(standard.MinValue);
                }
                catch (Exception ex)
                {
                    standard.MinValue = null;
                    XtraMessageBox.Show(ex.Message);
                    return;
                }
            }

            if (!String.IsNullOrEmpty(standard.MaxValue))
            {
                try
                {
                    Convert.ToDouble(standard.MaxValue);
                }
                catch (Exception ex)
                {
                    standard.MaxValue = null;
                    XtraMessageBox.Show(ex.Message);
                    return;
                }
            }

            if (!String.IsNullOrEmpty(standard.MaxValue) && !String.IsNullOrEmpty(standard.MinValue))
            {
                try
                {
                    if (Convert.ToDouble(standard.MinValue) > Convert.ToDouble(standard.MaxValue))
                    {
                        XtraMessageBox.Show(ResourceOverall.ValueCompareErr);
                        this.gridView1.SetRowCellValue(row, e.Column, null);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show(ex.Message);
                    return;
                }

            }
            db.Entry<StandardCustomer>(standard).State = EntityState.Modified;
            db.SaveChanges();
        }

        private void StandardCustomerMainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.gridView1.CloseEditor();
        }

        private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                e.Info.DisplayText = e.RowHandle.ToString();
            }

        }

        private void ButtonItem_ChangeOrder_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FlyHorse.LIMS.WinApp.OtherForms.SetOrderForm form = new OtherForms.SetOrderForm(ChangeOrder);
            form.ShowDialog();
        }

        private void ChangeOrder(TestItem testItem, int order)
        {
            int count = ChangeOrderBll(testItem, order);
            XtraMessageBox.Show(ResourceOverall.EditSucceed + "(" + count + ")");
            InitGrid();
        }



        /// <summary>
        /// 批量删除客户标准
        /// </summary>
        /// <param name="standardList"></param>
        /// <returns></returns>
        public int BulkDelete(List<StandardCustomer> standardList)
        {
            foreach (var standard in standardList)
            {
                StandardCustomer standardCust = db.StandardCustomers.Find(standard.StandardCustomerID);
                db.Set<StandardCustomer>().Remove(standardCust);
            }
            return db.SaveChanges();
        }

        /// <summary>
        /// 批量修改客户标准的顺序
        /// </summary>
        /// <param name="testItem"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        public int ChangeOrderBll(TestItem testItem, int order)
        {
            var standardList = db.StandardCustomers.Where(m => m.TestItemID == testItem.TestItemID);
            foreach (var standard in standardList)
            {
                standard.FormOrder = order;
            }
            return db.SaveChanges();
        }

        private void ButtonItem_Print_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            if (!this.gridControl1.IsPrintingAvailable)
            {
                MessageBox.Show("The 'DevExpress.XtraPrinting' library is not found", "Error");
                return;
            }

            // Open the Preview window.
            this.gridControl1.ShowPrintPreview();

        }
    }
}